package naga.x.net.impl.pomelo;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import naga.x.App;
import naga.x.net.ClientSessionService;
import naga.x.net.codec.PacketDecoder;
import naga.x.net.codec.PacketEncoder;
import naga.x.net.codec.StickPacketDecoder;
import naga.x.net.impl.websocket.WebSocketDecoder;
import naga.x.net.impl.websocket.WebSocketEncoder;

public class PomeloClientSessionService extends ClientSessionService {
	
	static class Encoder extends ProtocolEncoderAdapter {
		private PacketEncoder pomelo, websocket;
		Encoder(PacketEncoder pomelo, PacketEncoder websocket) {
			this.pomelo = pomelo;
			this.websocket = websocket;
		}
		@Override
		public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
			Object buf = pomelo.encode(session, message);
			if (buf != null) {
				buf = websocket.encode(session, buf);
				if (buf != null) {
					out.write(buf);
				}
			}
		}
	}
	
	static class Decoder extends StickPacketDecoder {
		private PacketDecoder websocket, pomelo;
		Decoder(PacketDecoder websocket, PacketDecoder pomelo) {
			this.websocket = websocket;
			this.pomelo = pomelo;
		}
		@Override
		protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
			Object buf = websocket.decode(session, in);
			if (buf != null) {
				if (buf instanceof IoBuffer) {
					buf = pomelo.decode(session, (IoBuffer) buf);
					if (buf != null) {
						out.write(buf);
					}
				}
				return true;
			}
			return false;
		}
	}

	public PomeloClientSessionService() {
	}
	
	@Override
	protected IoFilter getCodecFilter() {
		return new ProtocolCodecFilter(
						new Encoder(new PomeloEncoder(), new WebSocketEncoder()),
						new Decoder(new WebSocketDecoder(), new PomeloDecoder())
						);
	}

	@Override
	protected int getPort() {
//		return App.getApp().getConfig().getIntValue(Config.WEBSOCKET_PORT);
		return App.getApp().getConfig().port;
	}
	
	@Override
	public String getId() {
		return "POMELO";
	}

	@Override
	protected boolean isSslEnable() {
		return App.getApp().getConfig().sslEnable;
	}

	@Override
	protected String getSslKeyStore() {
		return App.getApp().getConfig().sslKeyStorePath;
	}

	@Override
	protected String getSslKeyPassword() {
		return App.getApp().getConfig().sslKeyPassword;
	}
	

}
